import React, { Component } from 'react'
import { hashHistory } from 'react-router'
import { Button, InputItem, Toast } from 'antd-mobile'
import { createForm } from 'rc-form'

import { config, myFetch, helper } from 'appRoot/components/utils'

class LoginForm extends Component {
  constructor() {
    super()
    
    // 如果已经登录了则直接到首页
    if (sessionStorage.token) {
      hashHistory.push('/')
    }

    this.login = this.login.bind(this)
  }
  render() {
    const { getFieldProps } = this.props.form
    return (
        <div className="rt-box-login">
          <InputItem
            type="phone"
            {...getFieldProps('mobile', {
              initialValue: '',
            })}
            placeholder="请输入手机号码"
            clear
          />
          <InputItem
            type="password"
            {...getFieldProps('password', {
              initialValue: '',
            })}
            placeholder="请输入密码"
            clear
          />
          <Button onClick={(e)=>this.login()} className="rt-main-dl">登 录</Button>
        </div>
      )
  }
  
  /**
   * 登录操作
   * @memberOf LoginForm
   */
  login() {
    const { getFieldProps, getFieldValue } = this.props.form
    let mobile = getFieldValue('mobile')
    if (!mobile) {
      Toast.fail('请输入手机号码', 1.2)
      return
    }
    mobile = mobile.replace(/\s/g, '')
    if (!config.pattern.mobile.test(mobile)) {
      Toast.fail('请填写有效手机号码', 1.2)
      return
    }
    const password = getFieldValue('password')
    if (!password || password.trim() === '') {
      Toast.fail('请输入密码', 1.2)
      return
    }
    const options = {
      method: 'POST',
      body: JSON.stringify({
        username: mobile,
        password: password
      })
    }
    myFetch(`${config.rootApi}/user/login`, options)
      .then((rs) => {
        if (rs && rs.value) {
          sessionStorage.setItem('token', rs.value)
          sessionStorage.setItem('mobile', mobile)
          hashHistory.push('/main')
        }
      })
  }
}

export default createForm()(LoginForm)